<template>
    <div class="allmap" :id="defaultOptions.el"></div>
</template>
<script>
// 高德地图组件
import { MyMap } from '@/common/js/aMap'
import AMapLoader from '@amap/amap-jsapi-loader'

// 地图安全密钥
window._AMapSecurityConfig = {
    securityJsCode: '22fb032673277bc934d1785f4ba3f1e4'
}

export default ({
    name: 'AMap',
    props: {
        options: Object,    // 初始化基础参数
        data: Object        // 初始化数据
    },
    data() {
        return {
            defaultOptions: {
                el: 'allmap'
            },
            myMap: null,
            datas: []       // 标记点数据
        }
    },
    methods: {
        callback: function(res, datas = []) {
            this.datas = [ ...datas ]
            this.$emit('update', res)
        },
        setMarker(obj) {
            if (obj && this.myMap) {
                // this.myMap.getLocation(obj) // 目前高德地址逆解析坐标有误差
                this.myMap.search(obj) // 采用搜索的方式坐标更为精准
            }
        },
        async createdMap(initMap) {
            try {
                if (this.myMap) {
                    initMap()
                } else {
                    this.defaultOptions = { ...this.defaultOptions, ...this.options }
                    await AMapLoader.load({
                        key: "20bd4c85c7dc4e87d3683be0e83a17c0", // 申请好的Web端开发者Key
                        version: "2.0",      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                        plugins: [''],       // 需要使用的的插件列表，如比例尺'AMap.Scale'等
                    })
                    this.myMap = new MyMap({
                        el: this.defaultOptions.el,
                        cb: this.callback
                    })
                    initMap()
                }
            } catch(error) {
                this.$message.error(`${error}`)
            }
        }
    },
    watch: {
        "data": {
            immediate: true,
            handler: function(val) {
                this.createdMap(() => {
                    if (val && val.point) {
                        val.lnglat = val.point
                        this.myMap.setData(val)
                        this.myMap.setMarker(val.point, true, this.datas.length)
                    }
                })
            }
        }
    }
})
</script>
<style lang="scss" scoped>
.allmap /deep/ {
    width: 100%;
    height: 100%;
    min-width: 300px;
    min-height: 300px;
    position: relative;
    .amap-info-content {
        border: 1px solid var(--base-border-color-deep-1);
        border-bottom-width: 0;
        border-radius: 4px;
        min-width: 220px;
    }
    .map-infowindow {
        padding: 4px
    }
    .map-infowindow .map-infowindow-title {
        font-weight: bold;
        margin-bottom: 8px;
    }
    .amap-logo, .amap-copyright {
        display: none!important;
    }
}
</style>